import { toast } from "../../components/Toast/Toast";
import { keywordApi } from "../backend/server";
import { KeywordListType } from "../domain/keyword";
// import { getKeywordList } from "../common/common";
// import { updateKeywordList } from "../common/common";

// export const extractKeyworld = (str: string,key: string)=>
//    str.replace(key+" ", "").split(" ");
// const urlReg: RegExp = new RegExp(/http|#|www|\.|\//);
const urlReg: RegExp = new RegExp(/\./);
// const urlReg: RegExp = new RegExp(
//   /^(https:\/\/|http:\/\/){0,1}[a-zA-Z0-9]*?\.[a-zA-Z0-9].*?/
// );

export const getUrl = (entry: string[]) =>
  entry.find((val) => urlReg.test(val))?.split("?")[0] || "";

export const getKey = (entry: string[], url: string) =>
  entry.find((val) => val != url) || "";

export async function install(
  val: string,
  keywordList: KeywordListType,
  clearInputCallBack: () => void
): Promise<void> {
  const entry: string[] = val.replace("add ", "").split(" ");
  const url = getUrl(entry);
  const key = getKey(entry, url);
  if (!key || !url) {
    toast("please check your key or url spell");
    return;
  }

  // if (keywordList.findIndex((val) => val.keyName === key) > -1) {
  //   let shortcut = keywordList.find((ele) => ele.keyName === key)?.url;
  //   toast("the key already exist! url is: " + shortcut);
  //   return;
  // }

  // await keywordApi.addPlaceholder(key, url);
  await keywordApi.addPlaceholder({ keyName: key, url: url });
  toast(url.startsWith("http") ? url : "http://" + url);
  // refreshKeywordList();
  clearInputCallBack();
}
